<?php
/**
 * 商品列表
 *
 ***/


defined('IN_NWIDC') or exit('Access Invalid!');

function getCombinationToString($arr, $m) {
    $m = count($arr);
    if ($m == 1) {
        return $arr;
    }
    $result = array();

    $tmpArr = $arr;
    unset($tmpArr[0]);
    for ($i = 0; $i < count($arr); $i++) {
        $s = $arr[$i];
        $ret = getCombinationToString(array_values($tmpArr), ($m - 1), $result);

        foreach ($ret as $row) {
            $result[] = $s . '.*' . $row;
        }
    }

    return $result;
}

function arrangement($arr, $len = 0, $str = "") {
    $res = array();
    $arr_len = count($arr);
    if ($len == 0) {
        $res[] = $str;
	} else {
        for ($i = 0; $i < $arr_len; $i++) {
            $tmp = array_shift($arr);
            $res = array_merge($res,arrangement($arr, $len - 1, $str . ".*" . $tmp));
            array_push($arr, $tmp);
        }
    }
    return $res;

}

function getCombines($arr, $len = 0, $str = "") {
    $res = arrangement($arr,count($arr));
    return $res;
    $str = '1=12,2=34,3=14,4=23';
    $_str = explode(',', $str);
    $_str = $arr;
    $_str = array_reverse($_str);
    $_key = array();
    $tree = array();
    foreach ($_str as $v) {
        $str = explode('=', $v);
        $_key[] = $str[0];
        $str = str_split($str[1]);
        $_tree = array();
        foreach ($str as $node) {
            if (empty($tree)):
                $_tree[][] = $node;
            else:
                foreach ($tree as $_node) $_tree[] = str_split(implode($_node) . $node);
            endif;
        }
        $tree = $_tree;
    }
    foreach ($tree as $v) {
        $str = array();
        foreach ($v as $_k => $_v) $str[] = $_key[$_k] . '=' . $_v;
        echo implode(',', array_reverse($str)), '<br>';
    }
}

class searchControl extends BaseHomeControl {


    //每页显示商品数
    var $PAGESIZE = 24;

    //模型对象
    private $_model_search;

    public function indexOp() {
        Language::read('home_goods_class_index');
        $this->_model_search = Model('search');
        //显示左侧分类
        //默认分类，从而显示相应的属性和品牌
        $default_classid = intval($_GET['cate_id']);
        if (intval($_GET['cate_id']) > 0) {
            $goods_class_array = $this->_model_search->getLeftCategory(array($_GET['cate_id']));
        } elseif ($_GET['keyword'] != '') {
            //从TAG中查找分类
            $goods_class_array = $this->_model_search->getTagCategory($_GET['keyword']);
            //取出第一个分类作为默认分类，从而显示相应的属性和品牌
            $default_classid = $goods_class_array[0];
            $goods_class_array = $this->_model_search->getLeftCategory($goods_class_array, 1);;
        }
        Tpl::output('goods_class_array', $goods_class_array);
        Tpl::output('default_classid', $default_classid);

        //优先从全文索引库里查找
        list($indexer_ids,$indexer_count) = $this->_model_search->indexerSearch($_GET,$this->PAGESIZE);
// print_r($default_classid);exit;
        //获得经过属性过滤的商品信息
        list($goods_param, $brand_array, $attr_array, $checked_brand, $checked_attr) = $this->_model_search->getAttrCopy($_GET, $default_classid);




        // $brand_array = Model('goods_class')->get_class_binding_brand($_GET['cate_id']);
        // // 被选中的品牌
        // $brand_id = intval($_GET['b_id']);
        // if ($brand_id > 0 && !empty($brand_array)){
        //     $checked_brand = array();
        //     if(isset($brand_array[$brand_id])){
        //         $checked_brand[$brand_id]['brand_name'] = $brand_array[$brand_id]['brand_name'];
        //     }
        // }



        // //属性列表
        // $class_info = Model()->table('goods_class')->where(array('gc_id'=>$_GET['cate_id']))->find();
        // $type_id = $class_info['type_id'];
        // // print_r($class_info);exit;
        // $model_attribute = Model('attribute');
        // $attribute_list = $model_attribute->getAttributeShowList(array('type_id' => $type_id), 'attr_id,attr_name');
        // $attributevalue_list = $model_attribute->getAttributeValueList(array('type_id' => $type_id), 'attr_value_id,attr_value_name,attr_id');
        // $attributevalue_list = array_under_reset($attributevalue_list, 'attr_id', 2);
        // $attr_array = array();
        // if (!empty($attribute_list)) {
        //     foreach ($attribute_list as $val) {
        //         $attr_array[$val['attr_id']]['name'] = $val['attr_name'];
        //         $tpl_array = array_under_reset($attributevalue_list[$val['attr_id']], 'attr_value_id');
        //         $attr_array[$val['attr_id']]['value'] = $tpl_array;
        //     }
        // }
        // //根据属性筛选s
        // if(!empty($_GET['a_id'])){
        //     $attr_ids = explode('_', $_GET['a_id']);
        // }
        // // 根据属性查找商品
        // if (is_array($attr_ids)) {
        //     // 商品id数组
        //     $goodsid_array = array();
        //     $data['sign'] = false;
        //     foreach ($attr_ids as $val) {
        //         $where = array();
        //         $where['attr_value_id'] = $val;
        //         if ($data['sign']) {
        //             $where['goods_id'] = array('in', $goodsid_array);
        //         }
        //         $goodsattrindex_list = Model('goods_attr_index')->getGoodsAttrIndexList($where, 'goods_id');
        //         if (!empty($goodsattrindex_list)) {
        //             $data['sign'] = true;
        //             $tpl_goodsid_array = array();
        //             foreach ($goodsattrindex_list as $val) {
        //                 $tpl_goodsid_array[] = $val['goods_id'];
        //             }
        //             $goodsid_array = $tpl_goodsid_array;
        //         } else {
        //             $data['goodsid_array'] = $goodsid_array = array();
        //             $data['sign'] = false;
        //             break;
        //         }
        //     }
        //     if ($data['sign']) {
        //         $data['goodsid_array'] = $goodsid_array;
        //     }
        // }
        // $goods_param = $data;
        // //e
        // // 被选中的属性
        // if(is_array($attr_ids) && !empty($attr_array)){
        //     $checked_attr = array();
        //     foreach ($attr_ids as $s){
        //         foreach ($attr_array as $k=>$d){
        //             if(isset($d['value'][$s])){
        //                 $checked_attr[$k]['attr_name']      = $d['name'];
        //                 $checked_attr[$k]['attr_value_id']  = $s;
        //                 $checked_attr[$k]['attr_value_name']= $d['value'][$s]['attr_value_name'];
        //             }
        //         }
        //     }
        // }
        // print_r($goods_param);exit;

        Tpl::output('brand_array', $brand_array);
        Tpl::output('attr_array', $attr_array);
        Tpl::output('checked_brand', $checked_brand);
        Tpl::output('checked_attr', $checked_attr);

        //处理排序
        $order = 'is_own_shop desc,goods_id desc';
        if (in_array($_GET['key'],array('1','2','3'))) {
            $sequence = $_GET['order'] == '1' ? 'asc' : 'desc';
            $order = str_replace(array('1','2','3'), array('goods_salenum','goods_click','goods_promotion_price'), $_GET['key']);
            $order .= ' '.$sequence;
        }
        $model_goods = Model('goods');
        // 字段
        $fields = "goods_id,goods_commonid,goods_name,goods_jingle,gc_id,store_id,store_name,goods_price,goods_promotion_price,goods_promotion_type,goods_marketprice,goods_storage,goods_image,goods_freight,goods_salenum,color_id,evaluation_good_star,evaluation_count,is_virtual,is_fcode,is_appoint,is_presell,have_gift,open_tax";

        $condition = array();
        if (is_array($indexer_ids)) {

            //商品主键搜索
            $condition['goods_id'] = array('in',$indexer_ids);
            $goods_list = $model_goods->getGoodsOnlineList($condition, $fields, 0, $order, $this->PAGESIZE, null, false);

            //如果有商品下架等情况，则删除下架商品的搜索索引信息
            if (count($goods_list) != count($indexer_ids)) {
                $this->_model_search->delInvalidGoods($goods_list, $indexer_ids);
            }

            pagecmd('setEachNum',$this->PAGESIZE);
            pagecmd('setTotalNum',$indexer_count);

        } else {
            //执行正常搜索
            if (isset($goods_param['class'])) {
                $condition['gc_id_'.$goods_param['class']['depth']] = $goods_param['class']['gc_id'];
            }
            if (intval($_GET['b_id']) > 0) {
                $condition['brand_id'] = intval($_GET['b_id']);
            }
            if ($_GET['keyword'] != '') {
                $arr = preg_split("/\s+|[　]+/", $_GET['keyword']);
                $result = getCombines($arr, count($arr));
                $condition['goods_name|goods_jingle'] = array('regexp', implode('|', $result));
            }
            if (intval($_GET['area_id']) > 0) {
                $condition['areaid_1'] = intval($_GET['area_id']);
            }
            if ($_GET['type'] == 1) {
                $condition['is_own_shop'] = 1;
            }
            if ($_GET['gift'] == 1) {
                $condition['have_gift'] = 1;
            }
            if (isset($goods_param['goodsid_array'])){
                $condition['goods_id'] = array('in', $goods_param['goodsid_array']);
            }
            if(_config('template_name') == 'mln'){
                $this->PAGESIZE = 24;
            }
            $goods_list = $model_goods->getGoodsListByColorDistinct($condition, $fields, $order, $this->PAGESIZE);
        }

        Tpl::output('show_page1', $model_goods->showpage(4));
        Tpl::output('show_page', $model_goods->showpage(5));

        // 商品多图
        if (!empty($goods_list)) {
            $commonid_array = array(); // 商品公共id数组
            $storeid_array = array();       // 店铺id数组
            foreach ($goods_list as $value) {
                $commonid_array[] = $value['goods_commonid'];
                $storeid_array[] = $value['store_id'];
            }
            $commonid_array = array_unique($commonid_array);
            $storeid_array = array_unique($storeid_array);

            // 商品多图
            $goodsimage_more = Model('goods')->getGoodsImageList(array('goods_commonid' => array('in', $commonid_array)));

            // 店铺
            $store_list = Model('store')->getStoreMemberIDList($storeid_array);
            //搜索的关键字
            $search_keyword = trim($_GET['keyword']);
            foreach ($goods_list as $key => $value) {
                // 商品多图
                foreach ($goodsimage_more as $v) {
                    if ($value['goods_commonid'] == $v['goods_commonid'] && $value['store_id'] == $v['store_id'] && $value['color_id'] == $v['color_id']) {
                        $goods_list[$key]['image'][] = $v;
                    }
                }
                // 店铺的开店会员编号
                $store_id = $value['store_id'];
                $goods_list[$key]['member_id'] = $store_list[$store_id]['member_id'];
                $goods_list[$key]['store_domain'] = $store_list[$store_id]['store_domain'];
                //将关键字置红
                if ($search_keyword){
                    $goods_list[$key]['goods_name_highlight'] = str_replace($search_keyword,'<font style="color:#f00;">'.$search_keyword.'</font>',$value['goods_name']);
                } else {
                    $goods_list[$key]['goods_name_highlight'] = $value['goods_name'];
                }
                //是否促销
                $condition = array();
                $condition['state'] = 1;
                $condition['goods_id'] = $value['goods_id'];
                $condition['start_time'] = array('elt',TIMESTAMP);
                $condition['end_time'] = array('gt',TIMESTAMP);
                $is_discount = Model()->table("p_xianshi_goods")->where($condition)->find();
                if(is_array($is_discount)&& count($is_discount)>1){
                    $goods_list[$key]['is_discount'] = 1;
                }
                
            }
        }
        //获取店铺信息
        $model_store = Model('store');
        foreach ($goods_list as $key => $value) {
            $goods_list[$key]['store_info'] = $model_store->getStoreInfoByID($value['store_id']);
        }
        Tpl::output('goods_list', $goods_list);
        if ($_GET['keyword'] != ''){
            Tpl::output('show_keyword',  $_GET['keyword']);
        } else {
            Tpl::output('show_keyword',  $goods_param['class']['gc_name']);
        }

        $model_goods_class = Model('goods_class');

        // SEO
        if ($_GET['keyword'] == '') {
            $seo_class_name = $goods_param['class']['gc_name'];
            if (is_numeric($_GET['cate_id']) && empty($_GET['keyword'])) {
                $seo_info = $model_goods_class->getKeyWords(intval($_GET['cate_id']));
                if (empty($seo_info[1])) {
                    $seo_info[1] = C('site_name') . ' - ' . $seo_class_name;
                }
                Model('seo')->type($seo_info)->param(array('name' => $seo_class_name))->show();
            }
        } elseif ($_GET['keyword'] != '') {
            Tpl::output('html_title', (empty($_GET['keyword']) ? '' : $_GET['keyword'] . ' - ') . C('site_name') . L('nc_common_search'));
        }

        // 当前位置导航
        $nav_link_list = $model_goods_class->getGoodsClassNav(intval($_GET['cate_id']));
        Tpl::output('nav_link_list', $nav_link_list );

        // 得到自定义导航信息
        $nav_id = intval($_GET['nav_id']) ? intval($_GET['nav_id']) : 0;
        Tpl::output('index_sign', $nav_id);

        // 地区
        $province_array = Model('area')->getTopLevelAreas();
        Tpl::output('province_array', $province_array);

        loadfunc('search');

        // 浏览过的商品
        $viewed_goods = Model('goods_browse')->getViewedGoodsList($_SESSION['member_id'],20);
        Tpl::output('viewed_goods',$viewed_goods);
        Tpl::showpage('search');
    }

    /**
     * 获得推荐商品
     */
    public function get_booth_goodsOp() {
        $gc_id = $_GET['cate_id'];
        if ($gc_id <= 0) {
            return false;
        }
        // 获取分类id及其所有子集分类id
        $goods_class = Model('goods_class')->getGoodsClassForCacheModel();
        if (empty($goods_class[$gc_id])) {
            return false;
        }
        $child = (!empty($goods_class[$gc_id]['child'])) ? explode(',', $goods_class[$gc_id]['child']) : array();
        $childchild = (!empty($goods_class[$gc_id]['childchild'])) ? explode(',', $goods_class[$gc_id]['childchild']) : array();
        $gcid_array = array_merge(array($gc_id), $child, $childchild);
        // 查询添加到推荐展位中的商品id
        $boothgoods_list = Model('p_booth')->getBoothGoodsList(array('gc_id' => array('in', $gcid_array)), 'goods_id', 0, 4, 'rand()');
        if (empty($boothgoods_list)) {
            return false;
        }

        $goodsid_array = array();
        foreach ($boothgoods_list as $val) {
            $goodsid_array[] = $val['goods_id'];
        }

        $fieldstr = "goods_id,goods_commonid,goods_name,goods_jingle,store_id,store_name,goods_price,goods_promotion_price,goods_promotion_type,goods_marketprice,goods_storage,goods_image,goods_freight,goods_salenum,color_id,evaluation_count";
        $goods_list = Model('goods')->getGoodsOnlineList(array('goods_id' => array('in', $goodsid_array)), $fieldstr);
        if (empty($goods_list)) {
            return false;
        }

        Tpl::output('goods_list', $goods_list);
        Tpl::showpage('goods.booth', 'null_layout');
    }

	public function auto_completeOp() {
	    try {
    	    require(BASE_DATA_PATH.'/api/xs/lib/XS.php');
    	    $obj_doc = new XSDocument();
    	    $obj_xs = new XS(C('fullindexer.appname'));
    	    $obj_index = $obj_xs->index;
    	    $obj_search = $obj_xs->search;
    	    $obj_search->setCharset(CHARSET);
            $corrected = $obj_search->getExpandedQuery($_GET['term']);
            if (count($corrected) !== 0) {
                $data = array();
                foreach ($corrected as $word)
                {
                    $row['id'] = $word;
                    $row['label'] = $word;
                    $row['value'] = $word;
                    $data[] = $row;
                }
                exit(json_encode($data));
            }
        } catch (XSException $e) {
            if (is_object($obj_index)) {
                $obj_index->flushIndex();
            }
//             Log::record('search\auto_complete'.$e->getMessage(),Log::RUN);
        }
	}

	/**
	 * 获得猜你喜欢
	 */
	public function get_guesslikeOp(){
	    $goodslist = Model('goods_browse')->getGuessLikeGoods($_SESSION['member_id'], 20);
        foreach($goodslist as $k=>$v){
            $goods_info = Model()->table('goods')->find($v['goods_id']);
            $goodslist[$k]['goods_comment'] = $goods_info['evaluation_count'];
        }
	    Tpl::output('goodslist',$goodslist);
	    Tpl::showpage('goods_guesslike','null_layout');
	}
}
